#include "cli_auth.h"
#include "cli_network.h"
#include "cli_handler.h"
#include "beautify.h"

#include <termios.h>

static void get_password(char *password, size_t size)
{
    struct termios oldt, newt;
    int i = 0;
    char c;

    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;

    newt.c_lflag &= ~(ECHO); // 关闭回显

    tcsetattr(STDIN_FILENO, TCSANOW, &newt);

    printf("🧐: ");
    fflush(stdout);

    while (i < size - 1 && read(STDIN_FILENO, &c, 1) == 1 && c != '\n' && c != '\r')
    {
        password[i++] = c;
    }
    password[i] = '\0';

    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    printf("\n");
}

int login(Command_t *command, UserInfo_t *user, int socket_fd)
{
    sendAll(socket_fd, command, sizeof(Command_t), 0); // 先发送命令结构体

    user->if_login = true;
    CAT_MSG("用户名喵~:");
    scanf("%50s", user->name);

    CAT_MSG("密码喵~:");

    char password[51];
    get_password(password, sizeof(password));

    strcpy(user->password, password);
    char c;
    while ((c = getchar()) != '\n')
        ;

    sendAll(socket_fd, user, sizeof(UserInfo_t), 0);

    Response_t resp;
    memset(&resp, 0, sizeof(Response_t));

    if (recvAll(socket_fd, &resp, sizeof(resp) - sizeof(char *), 0) == 0)
    {
        PRINT_ERROR("Server closed connection while receiving response");
        return -1;
    }
    // 接收可变大小的 resp 部分
    if (resp.resp_len > 0)
    {
        resp.resp = (char *)malloc(resp.resp_len + 1);
        if (resp.resp == NULL)
        {
            PRINT_ERROR("failed to malloc resp.resp");
            return -1;
        }

        if (recvAll(socket_fd, resp.resp, resp.resp_len, 0) == 0)
        {
            PRINT_ERROR("Server closed connection while receiving response");
            free(resp.resp);
            return -1;
        }
        resp.resp[resp.resp_len] = '\0'; // 确保字符串以 '\0' 结尾
    }
    else
    {
        resp.resp = NULL;
    }

    if (!resp.if_success)
    {
        CAT_MSG("登录失败了喵~ 请检查你的用户名和密码，重新试试喵~");
        if (resp.resp != NULL)
        {
            puts(resp.resp);
            free(resp.resp);
        }
        return -1;
    }

    recvAll(socket_fd, user, sizeof(UserInfo_t), 0);

    // PRINT_DEBUG("user->jwt_token: %s", user->jwt_token);
    CAT_MSG("你已经成功登录了喵喵云盘，祝你使用愉快喵 ~");
    return 0;
}

int signUp(Command_t *command, UserInfo_t *user, int socket_fd)
{
    sendAll(socket_fd, command, sizeof(Command_t), 0); // 先发送命令结构体

    user->if_login = false;
    while (1)
    {
        char name[51] = {0};
        CAT_MSG("用户名喵~:");
        scanf("%50s", name);

        char pass1[51] = {0};
        CAT_MSG("密码喵~:");
        get_password(pass1, sizeof(pass1));

        char pass2[51] = {0};
        CAT_MSG("请再次输入密码确认喵~:");
        get_password(pass2, sizeof(pass2));

        if (strcmp(pass1, pass2) == 0)
        {
            strcpy(user->name, name);
            strcpy(user->password, pass1);
            char c;
            while ((c = getchar()) != '\n')
                ;
            break;
        }
        else
        {
            CAT_MSG("两次输入的密码不一致呢，请重新输入并注册吧！(｡•́︿•̀｡)");
        }
    }

    sendAll(socket_fd, user, sizeof(UserInfo_t), 0);

    Response_t resp;
    memset(&resp, 0, sizeof(Response_t));

    if (recvAll(socket_fd, &resp, sizeof(resp) - sizeof(char *), 0) == 0)
    {
        PRINT_ERROR("Server closed connection while receiving response");
        return -1;
    }
    // 接收可变大小的 resp 部分
    if (resp.resp_len > 0)
    {
        resp.resp = (char *)malloc(resp.resp_len + 1);
        if (resp.resp == NULL)
        {
            PRINT_ERROR("failed to malloc resp.resp");
            return -1;
        }

        if (recvAll(socket_fd, resp.resp, resp.resp_len, 0) == 0)
        {
            PRINT_ERROR("Server closed connection while receiving response");
            free(resp.resp);
            return -1;
        }
        resp.resp[resp.resp_len] = '\0'; // 确保字符串以 '\0' 结尾
    }
    else
    {
        resp.resp = NULL;
    }

    if (!resp.if_success)
    {
        CAT_MSG("喵~ 注册失败了呢，请检查你的信息再试一次吧 (｡•́︿•̀｡)");
        if (resp.resp != NULL)
        {
            puts(resp.resp);
            free(resp.resp);
        }
        return -1;
    }

    CAT_MSG("喵喵~ 注册成功啦！欢迎加入我们的大家庭 (≧∇≦)ﾉ");
    CAT_MSG("现在请登录才能使用哦~");
    return 0;
}